﻿<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 80% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDypXt_xTgAMOTpSEdwmPXjUA0JGGbyXhY&sensor=false">
    </script>
    <script type="text/javascript">
	//Map
	var map;
	//Lat,Lng of init position
	var init_lat=-34.397;
	var init_lng=150.644;
	//Zoom
	var zoomRate = 10;
	//Geocode : convert Address string to Location on map (Lat,Lng)
	//var geocoder;
	//Address string will be input by user
	var nt_address="";
	//Maker
	var nt_marker;
	var nt_markercount=0;
	//Info window
	var nt_infowindow;
	
/*Load function*/
	
       function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(init_lat,init_lng);
        var mapOptions = {
          zoom: zoomRate,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
		//Setup geocoder for new order marker
		google.maps.event.addListener(map,	'click',
						function(event) {
							newMarkerOrder(event.latLng);
						});
		//Set current pos center using HTML5
		placeMarkerCurrentPos();
      }
/*Convert address to location*/
      function codeAddress() {
        var address = document.getElementById('address').value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }
//Execute when input text change
		function placeChange() {
			var address = document.getElementById("address").value;
			var city = document.getElementById("city").value;
			var district = document.getElementById("district").value;
			//Checking if address is empty : get location of district if have
			if(address==""){
				address=district+","+city;
			}
			geocoder.geocode( { 'address': address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
					var pos = results[0].geometry.location;
					//Address after formated
					var formatted_address =  results[0].formatted_address;
					if (nt_markercount == 0) {
					nt_markercount++;
					nt_marker = new google.maps.Marker({
						position : pos,
						map : map,
						icon:"images/newpin.png",
						draggable : true,
						title : "NT Address",
						zIndex : 1
					});
					var infowindowMarkerNewOrder = {
						content : setContentNewOrderInfoWindow(
								formatted_address, pos.lat(), pos
										.lng())
					};
					infowindowNew = new google.maps.InfoWindow(
							infowindowMarkerNewOrder);
					infowindowNew.setContent(nt_address);
					nt_marker['infowindow'] = infowindowNew;
					infowindowNew.setContent(setContentNewOrderInfoWindow(
							formatted_address, pos.lat(),
									pos.lng()));
					if (infowindowNew) {
						infowindowNew.close();
					}
					infowindowNew.open(map, nt_marker);

					google.maps.event.addListener(nt_marker,'dragend',
									function() {
										map.setCenter(pos);
										geocoder.geocode({latLng : nt_marker.getPosition()},
														function(results1,status1) {
															if (status1 == google.maps.GeocoderStatus.OK) {
																nt_address = results1[0].formatted_address;
																infowindowNew.setContent(setContentNewOrderInfoWindow(
																				nt_address,
																				nt_marker.getPosition().lat(),
																				nt_marker.getPosition().lng()));
																if (infowindowNew) {
																	infowindowNew.close();
																}
																infowindowNew.open(map,nt_marker);
															} else {
																nt_marker.setPosition(pos);
																nt_address = 'Cannot determine address at this location.';
																alert(nt_address);
															}
														});
									});
				} else {
					nt_marker.setPosition(pos);
					infowindowNew.setContent(setContentNewOrderInfoWindow(
							formatted_address,
									pos.lat(),
									pos.lng()));
					if (infowindowNew) {
						infowindowNew.close();
					}
					infowindowNew.open(map, nt_marker);
				}
		         
		      } 
		      /* else {
		        alert("Geocode was not successful for the following reason: " + status);
		      }*/
		    });						
	}  
	// Place new order marker
	function newMarkerOrder(pos) {
		map.setCenter(pos);
		geocoder.geocode({latLng : pos},
			function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					nt_address = results[0].formatted_address;
					if (nt_markercount == 0) {
						nt_markercount++;
						nt_marker = new google.maps.Marker({
							position : pos,
							map : map,
							icon:"images/newpin.png",
							draggable : true,
							title : "New Order Marker",
							zIndex : 1
							});
						var infowindowMarkerNewOrder = {
							content : setContentNewOrderInfoWindow(nt_address, pos.lat(), pos.lng())};
							infowindowNew = new google.maps.InfoWindow(
								infowindowMarkerNewOrder);
								infowindowNew.setContent(nt_address);
								nt_marker['infowindow'] = infowindowNew;
								infowindowNew.setContent(setContentNewOrderInfoWindow(
								nt_address, pos.lat(),pos.lng()));
								if (infowindowNew) {
									infowindowNew.close();}
									infowindowNew.open(map, nt_marker);
									google.maps.event.addListener(nt_marker,'dragend',
									function() {
										map.setCenter(pos);
										geocoder.geocode({latLng : nt_marker.getPosition()},
											function(results1,status1) {
												if (status1 == google.maps.GeocoderStatus.OK) {
													nt_address = results1[0].formatted_address;
													infowindowNew.setContent(setContentNewOrderInfoWindow(
														nt_address,
														nt_marker.getPosition().lat(),
														nt_marker.getPosition().lng()));
														if (infowindowNew) {
															infowindowNew.close();}
														infowindowNew.open(map,nt_marker);
												} else {
														nt_marker.setPosition(pos);
														nt_address = 'Cannot determine address at this location.';
														alert(nt_address);
												}
											});
										});
								} else {
									nt_marker.setPosition(pos);
									infowindowNew.setContent(setContentNewOrderInfoWindow(
													nt_address,
													pos.lat(),
													pos.lng()));
									if (infowindowNew) {
										infowindowNew.close();
									}
									infowindowNew.open(map, nt_marker);
								}
							} else {
								nt_address = 'Cannot determine address at this location.';
							}
						});
		google.maps.event.addListener(nt_marker, "click", function() {
			if(infowindowNew){
				infowindowNew.close();
			}
			infowindowNew.open(map, nt_marker);
		});
		

	}
	//Place marker at current position
	function placeMarkerCurrentPos() {
		navigator.geolocation.getCurrentPosition(GetLocation);
		function GetLocation(location) {
			newMarkerOrder(new google.maps.LatLng(
					location.coords.latitude, location.coords.longitude));
		}
	}
	//Create html string for new order marker
	function setContentNewOrderInfoWindow(address, lat, lng) {

		var titleStyle = "style='color:red; font-size:14px; '";
		var latLngStyle = "style='color:green; font-size:12px; '";
		var htmlString = "<b "+titleStyle+">" + address + "</b></br>";
		
		return htmlString;
	}
    </script>
  </head>
  <body onload="initialize()">
	<div>
      <input id="address" type="textbox" placeholder="Địa chỉ">
	  <input id="city" type="textbox" placeholder="Thành phố">
	  <input id="district" type="textbox" placeholder="Quận huyện">
      <input type="button" value="Geocode" onclick="placeChange()">
    </div>
    <div id="map_canvas" style="width:100%; height:80%"></div>
  </body>
</html>